# -*- coding: utf-8 -*-
import time
from typing import List

from pubsub import pub
from selenium.webdriver.common.by import By

from zhi_dao import driver
from zhi_dao import driver_wait
from selenium.webdriver.support import expected_conditions as ec
from zhi_dao.entity.zhidao_section import ZhiDaoSection
from zhi_dao.zhidao_const import event_course_selected
from zhi_dao.zhidao_const import event_section_read_finished
from zhi_dao.http_log.zhidao_http_log import ZhiDaoWebDataObtain


class ZhiDaoSectionReader:

    sections: List[ZhiDaoSection]

    video_status_dict: dict

    small_video_status_dict: dict

    zhi_dao_web_data_obtain: ZhiDaoWebDataObtain

    def __init__(self):
        pub.subscribe(self.read_sections, event_course_selected)

    def read_sections(self) -> None:
        print("收到课程选择事件")
        section_li_list = []
        section_list: List[ZhiDaoSection] = []
        while len(section_li_list) == 0:
            sections_content_div = driver.find_element(
                By.XPATH, "//div[contains(@class, 'chapterScrollbar') and contains(@class, 'el-scrollbar')]")
            if sections_content_div is None:
                continue
            # sections_content_div = driver_wait.until(
            #     ec.presence_of_element_located(())
            section_li_list = sections_content_div.find_elements(
                By.XPATH, ".//li[contains(@class, 'clearfix') and contains(@class, 'video')]")
            for section_li in section_li_list:
                section_num_b = section_li.find_element(
                    By.XPATH, ".//b[contains(@class, 'pl5') and contains(@class, 'hour')]")
                section_name_div = section_li.find_element(By.XPATH, ".//span[@class='catalogue_title']")
                section_duration_span = section_li.find_element(
                    By.XPATH, ".//span[contains(@class, 'time') and contains(@class, 'fl')]")
                section_finished = True
                try:
                    section_finish_span = section_li.find_element(
                        By.XPATH, ".//b[contains(@class, 'fl') and contains(@class, 'time_icofinish')]")
                    if section_finish_span is None:
                        section_finished = False
                except Exception as e:
                    section_finished = False
                    # print(e)
                zhi_dao_course = ZhiDaoSection(num=section_num_b.text, name=section_name_div.text,
                                               duration=section_duration_span.text, finished=section_finished,
                                               element=section_li)
                section_list.append(zhi_dao_course)
        self.sections = section_list
        pub.sendMessage(event_section_read_finished, sections=section_list)

    def read_video_status_from_http(self):
        status_url = "https://studyservice-api.zhihuishu.com/gateway/t/v1/learning/queryStuyInfo"
        status_data = None
        while status_data is None:
            status_data = self.zhi_dao_web_data_obtain.get_data(status_url)
        self.video_status_dict = status_data.get("lesson")
        self.small_video_status_dict = status_data.get("lv")
        print(status_data)

    def read_videos_from_http(self):
        self.zhi_dao_web_data_obtain = ZhiDaoWebDataObtain(driver)
        self.read_video_status_from_http()
        section_list: List[ZhiDaoSection] = []
        video_list_url = "https://studyservice-api.zhihuishu.com/gateway/t/v1/learning/videolist"
        video_data = self.zhi_dao_web_data_obtain.get_data(video_list_url)
        chapter_list = video_data.get("videoChapterDtos")
        for chapter in chapter_list:
            lesson_list = chapter.get("videoLessons")
            # 章节编号
            chapter_num = str(chapter.get("orderNumber"))
            for lesson in lesson_list:
                # 小节id
                lesson_id = lesson.get("id")
                # 小节名称
                lesson_name = lesson.get("name")
                # 视频id
                video_id = lesson.get("videoId")
                # 视频编号
                lesson_num = str(lesson.get("orderNumber"))
                # 视频时长（秒）
                lesson_sec = str(lesson.get("videoSec"))
                video_status = self.video_status_dict.get(str(lesson_id))
                # 视频学习时长
                study_total_time = str(video_status.get("studyTotalTime"))
                # 是否已学完 0-否 1-是
                is_finished = video_status.get("watchState")
                small_lesson_list = lesson.get("videoSmallLessons")

                zhi_dao_course = ZhiDaoSection(num=chapter_num + "." + lesson_num, name=lesson_name,
                                               duration=study_total_time + "/" + lesson_sec, finished=is_finished,
                                               element=driver.find_element(By.TAG_NAME, "body"))
                section_list.append(zhi_dao_course)

        pub.sendMessage(event_section_read_finished, sections=section_list)
        print(section_list)

    def get_sections(self):
        return self.sections
